<script setup>
import { getWechatJsapi, getWithdrawPayInfo } from '@/api/jdb.js'
import { getWeChatJsApiLink } from '@/utils/common.js'
import { useRouter, useRoute } from 'vue-router'
import { ref } from 'vue'
import { closeToast, showFailToast, showLoadingToast } from 'vant'

const router = useRouter()
const route = useRoute()

const id = ref(undefined)
const mchId = ref(undefined)
const packageInfo = ref(undefined)
const price = ref(undefined)
const name = ref(undefined)
const phone = ref(undefined)

const loading = ref(true)

if(!!route.query.id) {
  id.value = route.query.id
}

const onClickLeft = () => {
  router.replace('/withdraw-history')
}

const getSignature = async () => {
  // let url = window.location.href.split('#')[0]
  // // let url = router.currentRoute.value.fullPath.split('#')[0]
  // getWechatJsapi({
  //   url: url
  getWechatJsapi({
    url: getWeChatJsApiLink()
  }).then(response => {
    // console.log(response, 'response')
    let debug = false
    if (import.meta.env.VITE_ENV === 'development') {
      debug = true
    }
    wx.config({
      debug: debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: import.meta.env.VITE_WE_CHAT_APP_ID, // 必填，公众号的唯一标识
      timestamp: response.data.timestamp, // 必填，生成签名的时间戳
      nonceStr: response.data.nonceStr, // 必填，生成签名的随机串
      signature: response.data.signature, // 必填，签名，见附录1
      jsApiList: ['checkJsApi', 'scanQRCode', 'requestMerchantTransfer']
      // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    })
  })
}

const init = async () => {
  const toast = showLoadingToast({
    message: '正在加载 ...',
    forbidClick: true,
    duration: 0
  })
  await getSignature()
  await getWithdrawPayInfo({
    id: id.value,
  }).then(response => {
    mchId.value = response.data.mchId
    packageInfo.value = response.data.packageInfo
    price.value = response.data.price
    name.value = response.data.name
    phone.value = response.data.phone
    closeToast()
    loading.value = false
  }).catch(error => {
    router.replace('/withdraw-history')
  })
}

const withdrawPay = async () => {
  wx.ready(function () {
    wx.checkJsApi({
      jsApiList: ['requestMerchantTransfer'],
      success: function (res) {
        if (res.checkResult['requestMerchantTransfer']) {
          WeixinJSBridge.invoke('requestMerchantTransfer', {
                mchId: mchId.value,
                appId: import.meta.env.VITE_WE_CHAT_APP_ID,
                package: packageInfo.value,
              },
              function (res) {
                if (res.err_msg === 'requestMerchantTransfer:ok') {
                  router.replace('/withdraw-pay-success?id=' + id.value)
                  // res.err_msg将在页面展示成功后返回应用时返回success，并不代表付款成功
                }
                if (res.err_msg === 'requestMerchantTransfer:fail') {
                  showFailToast('收款失败，请稍后重试')
                  // res.err_msg将在页面展示成功后返回应用时返回success，并不代表付款成功
                }
                if (res.err_msg === 'requestMerchantTransfer:cancel') {
                  showFailToast('用户取消收款')
                  //用户取消。发生场景：用户未确认收款，点击取消，返回APP
                  // res.err_msg将在页面展示成功后返回应用时返回success，并不代表付款成功
                }
              }
          );
        } else {
          alert('你的微信版本过低，请更新至最新版本。');
        }
      }
    });
  });
}

init()

</script>

<template>
  <div v-if="!loading">
    <van-nav-bar title="提现" fixed placeholder @click-left="onClickLeft" />
    <header class="withdraw-amount-header">提现金额：</header>
    <section class="withdraw-amount-section">
      <span class="withdraw-amount-currency">¥</span>
      <span class="withdraw-amount">{{price}}</span>
    </section>
    <div class="divider"></div>
    <header class="withdraw-user-header">提现用户：</header>
    <section class="withdraw-user-section">
      {{phone}}|{{name}}
    </section>

    <footer class="withdraw-footer">
      <van-button type="success" size="normal" block @click="withdrawPay">提现</van-button>
    </footer>
  </div>
</template>

<style scoped>
.withdraw-amount-header, .withdraw-user-header {
  font-size:16px;
  margin-top:32px;
  margin-left:20px;
}
.withdraw-amount-section {
  align-items: center;
  display: flex;
  margin-top:16px;
  margin-left:20px;
  margin-bottom: 20px;
}
.withdraw-amount-currency {
  font-size:16px;
}
.withdraw-amount {
  margin-left:12px;
  font-size:26px;
}
.withdraw-user-section {
  margin-top:16px;
  margin-left:20px;
  font-size:20px;
}
.divider {
  width: 100%;
  height: 10px;
  background-color:#eee;
}
.withdraw-footer {
  width: 90%;
  margin: 30px auto 0;
  text-align: center;
}
</style>
